package com.fjut.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fjut.model.wechat.Menu;
import com.fjut.mapper.MenuMapper;
import com.fjut.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjut.utils.ConstantPropertiesUtil;
import com.fjut.utils.HttpClientUtils;
import com.fjut.vo.wechat.MenuVo;
import lombok.SneakyThrows;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.fjut.dateBase.MenuField.PARENT_ID;

/**
 * <p>
 * 订单明细 订单明细 服务实现类
 * </p>
 *
 * @author DengTianxun
 * @since 2023-03-10
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    private static final Long PARENT_ID_VAL = 0L;
    private static final String HOST = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String GRANT_TYPE = "?grant_type=client_credential";
    private static final String APPID = "&appid=%s";
    private static final String SECRET = "&secret=%s";
    private static final String ACCESS_TOKEN = "access_token";

    @Autowired
    private WxMpService wxMpService;

    @Override
    public List<Menu> getMenuTreeList() {
        QueryWrapper<Menu> menuQueryWrapper = new QueryWrapper<>();
        menuQueryWrapper.eq(PARENT_ID, PARENT_ID_VAL);
        return baseMapper.selectList(menuQueryWrapper);
    }

    @Override
    public List<MenuVo> getMenuAllTreeList() {
        List<MenuVo> list = new ArrayList<>();
        List<Menu> menuList = baseMapper.selectList(null);
        List<Menu> oneMenuList = menuList.stream().filter(menu -> menu.getParentId().longValue() == 0).collect(Collectors.toList());
        for (Menu oneMenu : oneMenuList) {
            MenuVo oneMenuVo = new MenuVo();
            BeanUtils.copyProperties(oneMenu, oneMenuVo);
            List<Menu> twoMenuList = menuList.stream()
                    .filter(menu -> menu.getParentId().longValue() == oneMenu.getId())
                    .sorted(Comparator.comparing(Menu::getSort))
                    .collect(Collectors.toList());
            List<MenuVo> children = new ArrayList<>();
            for (Menu twoMenu : twoMenuList) {
                MenuVo twoMenuVo = new MenuVo();
                BeanUtils.copyProperties(twoMenu, twoMenuVo);
                children.add(twoMenuVo);
            }
            oneMenuVo.setChildren(children);
            list.add(oneMenuVo);
        }
        return list;
    }

    @Override
    public String getAccessToken() {
        try {
            //拼接请求地址
            StringBuffer buffer = new StringBuffer();
            buffer.append(HOST);
            buffer.append(GRANT_TYPE);
            buffer.append(APPID);
            buffer.append(SECRET);
            String url = String.format(buffer.toString(), ConstantPropertiesUtil.ACCESS_KEY_ID, ConstantPropertiesUtil.ACCESS_KEY_SECRET);
            String token = HttpClientUtils.get(url);
            String access_token = JSONObject.parseObject(token).getString(ACCESS_TOKEN);
            return access_token;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @SneakyThrows
    @Override
    public Boolean syncMenu() {
        List<MenuVo> menuVoList = getMenuAllTreeList();
        //菜单
        JSONArray buttonList = new JSONArray();
        for (MenuVo oneMenuVo : menuVoList) {
            JSONObject one = new JSONObject();
            one.put("name", oneMenuVo.getName());
            JSONArray subButton = new JSONArray();
            for (MenuVo twoMenuVo : oneMenuVo.getChildren()) {
                JSONObject view = new JSONObject();
                view.put("type", twoMenuVo.getType());
                if (twoMenuVo.getType().equals("view")) {
                    view.put("name", twoMenuVo.getName());
                    view.put("url", ConstantPropertiesUtil.REALM_NAME
                            + twoMenuVo.getUrl());
                } else {
                    view.put("name", twoMenuVo.getName());
                    view.put("key", twoMenuVo.getMenuKey());
                }
                subButton.add(view);
            }
            one.put("sub_button", subButton);
            buttonList.add(one);
        }
        //菜单
        JSONObject button = new JSONObject();
        button.put("button", buttonList);
        wxMpService.getMenuService().menuCreate(button.toJSONString());
        return true;
    }

    @Override
    public Boolean removeMenu() {
        try {
            wxMpService.getMenuService().menuDelete();
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        return true;
    }
}
